<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller;

use Hyperf\Config\Annotation\Value;
use Hyperf\Di\Exception\Exception;
use Hyperf\HttpMessage\Upload\UploadedFile;
use Hyperf\Swagger\Annotation as SA;
use Hyperf\Swagger\Request\SwaggerRequest;
use Imagick;
use ImagickDraw;

#[SA\HyperfServer('http')]
class UploadController extends Controller
{
    public static $uploadDir = '/uploads/';

    public static $imgAcceptMimiType = ['image/jpg', 'image/jpeg', 'image/png'];

    #[Value('server.settings.document_root')]
    public static $document_root;

    #[Value('server.servers.0.port')]
    public static $apiPort;

    public static $max_filesize = 500 * 1024;

    public static $img_size = 1024;

    #[SA\Post(path: '/upload/upload_image', summary: '上传图片', tags: ['上传接口'])]
    #[SA\Response(response: '200', content: new SA\JsonContent(ref: null))]
    public function uploadImage(SwaggerRequest $request)
    {
        try {
            $post = $request->post();
            $file = $request->file('file');

            // var_dump($post);
            // var_dump($file);
            // var_dump(self::$max_filesize);

            if ($post && isset($post['uploadType']) && $post['uploadType'] && $file) {
                $ext = $file->getExtension();
                // 图片检测安全
                $res = self::checkMimeType($file, $ext);
                if (! $res) {
                    throw new Exception('文件安全检测未通过');
                }
                /*if ($file->getSize() > self::$max_filesize) {
                    throw new Exception('图片大小不能超过' . (self::$max_filesize / 1024) . 'K');
                }*/

                //调整图片大小
                $imagick = new Imagick($file->getRealPath());
                $width = $imagick->getImageWidth();
                $height = $imagick->getImageHeight();

                //添加水印
                /*$draw = new ImagickDraw();
                $fontPath = '/usr/share/php81/test/imagick/tests/anonymous_pro_minus.ttf';
                $draw->setFillColor('#ffffff');
                $draw->setFont($fontPath);
                $draw->setFontSize(30);
                $imagick->annotateImage($draw, $width - 200, $height - 50, 0, '1234567890');*/


                if ($width > $height) {
                    if ($width > self::$img_size) {
                        $imagick->scaleImage(self::$img_size, 0);
                    }
                } else {
                    if ($height > self::$img_size) {
                        $imagick->scaleImage(0, self::$img_size);
                    }
                }
                $imagick->writeImage($file->getRealPath());

                // 生成新的文件名
                $newFileName = uniqid() . '.' . $file->getExtension();
                $path = self::$uploadDir . $post['uploadType'];
                if (! is_dir(self::$document_root . $path)) {
                    if (! mkdir(self::$document_root . $path, 0755, true)) {
                        throw new Exception('文件夹创建失败');
                    }
                }
                $path = $path . '/' . $newFileName;
                // var_dump(self::$document_root . $path);
                // 保存文件
                $file->moveTo(self::$document_root . $path);
                if (! $file->isMoved()) {
                    throw new Exception('图片保存失败');
                }

                $return = [
                    'message' => '图片上传成功',
                    'path' => getenv('API_HOST') . ':' . self::$apiPort . $path,
                ];
                var_dump('返回：' . var_export($return, true));
                return $this->response->success($return);
            }
            return $this->response->fail(-1, '数据提交错误');
        } catch (\Exception $e) {
            return $this->response->fail(-1, $e->getMessage());
        }
    }

    // 检测文件是否合法
    public static function checkMimeType(UploadedFile $uploadedFile, string $ext)
    {
        try {
            $filePath = $uploadedFile->getRealPath();

            $fileMimeType = mime_content_type($filePath);
            var_dump($fileMimeType);
            $isExist = in_array($fileMimeType, self::$imgAcceptMimiType);
            if (! $isExist) {
                throw new Exception('非允许mime types类型');
            }

            [$width, $height, $type, $attr] = getimagesize($filePath, $ext);
            if ($width <= 0 || $height <= 0) {
                return false;
            }
            return true;
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }
}
